package main

import (
	"fmt"
	"os/exec"
	_ "runtime"
	"sync"
	"time"

	"github.com/shirou/gopsutil/v3/process"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1) // 增加等待计数
	cmd := exec.Command("python", "demo.py")
	if err := cmd.Start(); err != nil {
		panic(err)
	}
	pid := cmd.Process.Pid
	// 创建监控协程
	fmt.Printf("pid: %d\n", pid)
	go monitorProcess(int32(pid), wg)
	fmt.Println("主协程等待中...")
	wg.Wait() // 安全阻塞，直到计数归零
	fmt.Println("主协程继续执行")
}

func monitorProcess(pid int32, wg sync.WaitGroup) {
	ticker := time.NewTicker(2 * time.Second) // 每2秒采集一次
	for range ticker.C {
		p, err := process.NewProcess(pid)
		if err != nil {
			// 进程已退出
			fmt.Println("进程退出")
			fmt.Println(err.Error())
			//return
		}

		// 获取CPU使用率
		cpuPercent, _ := p.Percent(time.Second)

		// 获取内存信息
		memInfo, _ := p.MemoryInfo()
		rss := memInfo.RSS // 常驻内存大小

		// 获取IO数据
		ioCounters, _ := p.IOCounters()

		fmt.Printf("PID: %d | CPU: %.2f%% | MEM: %v MB\n",
			pid, cpuPercent, rss/1024/1024)
		fmt.Printf(ioCounters.String() + "\n")
		fmt.Println()
	}
	defer func() {
		wg.Done()
		ticker.Stop()
	}()
}
